<!-- Dashboard.vue -->
<template>
  <div class="dashboard">
    <el-container>
      <el-aside width="200px">
        <el-menu default-active="home" class="el-menu-vertical" @select="handleSelect">
          <el-menu-item index="home">
            <span>首页</span>
          </el-menu-item>
          <el-menu-item index="user-management">
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="system-settings">
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-main>
        <dynamic-tabs
          :tabs="tabs"
          v-model:active-tab="activeTab"
          @remove-tab="removeTab"
          @tab-click="handleTabClick"
        />
        <keep-alive>
          <router-view></router-view>
      </keep-alive>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { provide, ref } from 'vue';
import { useRouter } from 'vue-router';
import DynamicTabs from '../components/DynamicTabs.vue';

const router = useRouter();
const tabs = ref([
  { label: '首页', name: 'home' },
]);
const activeTab = ref('home');

const menuItems = {
  home: { label: '首页' },
  'user-management': { label: '用户管理' },
  'system-settings': { label: '系统设置' },
};

const handleSelect = (index) => {
  const existingTab = tabs.value.find((tab) => tab.name === index);
  if (!existingTab) {
    tabs.value.push({
      label: menuItems[index].label,
      name: index,
    });
  }
  activeTab.value = index;
  router.push(`/dashboard/${index}`);
};

const removeTab = (targetName) => {
  const index = tabs.value.findIndex((tab) => tab.name === targetName);
  if (index !== -1) {
    tabs.value.splice(index, 1);
    if (activeTab.value === targetName) {
      const newActiveTab = tabs.value[index - 1] || tabs.value[0];
      activeTab.value = newActiveTab?.name || '';
      if (newActiveTab) {
        router.push(`/dashboard/${newActiveTab.name}`);
      } else {
        router.push('/dashboard');
      }
    }
  }
};

const handleTabClick = (tabName) => {
  activeTab.value = tabName;
  router.push(`/dashboard/${tabName}`);
};
</script>

<style scoped>
.dashboard {
  height: 100vh;
  display: flex;
}

.el-aside {
  background-color: #545c64;
  color: white;
}

.el-menu-vertical {
  border-right: none;
}

.el-main {
  background-color: #f5f5f5;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.el-tabs {
  margin-bottom: 20px;
}
</style>